package cn.zhixiangsingle.impl.organicTreatment;

import cn.zhixiangsingle.config.DynamicDataSourceContextHolder;
import cn.zhixiangsingle.dao.organicTreatment.OrganicTreatmentMapper;
import cn.zhixiangsingle.dao.site.SiteMapper;
import cn.zhixiangsingle.date.DateUtils;
import cn.zhixiangsingle.entity.base.IsEmptyUtils;
import cn.zhixiangsingle.entity.base.site.SiteData;
import cn.zhixiangsingle.entity.base.site.vo.SiteVO;
import cn.zhixiangsingle.entity.organicTreatment.dto.OrganicTreatmentDTO;
import cn.zhixiangsingle.entity.organicTreatment.vo.OrganicTreatmentVO;
import cn.zhixiangsingle.pagination.MyStartEndUtil;
import cn.zhixiangsingle.service.organicTreatment.OrganicTreatmentService;
import cn.zhixiangsingle.web.responsive.IStatusMessage;
import cn.zhixiangsingle.web.responsive.ResultBean;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;

/**
 * @author hhp
 * @description 餐厨有机处理业务层
 * @date 2019/11/6 9:28
 * @Copyright: 2019 www.zhixiangyun.net Inc. All rights reserved.
 * 注意：本内容仅限于浙江智飨科技内部传阅，禁止外泄以及用于其他的商业目
 */
@Service(version = "1.0.0", interfaceClass = OrganicTreatmentService.class)
public class OrganicTreatmentServiceImpl implements OrganicTreatmentService {
    private static final Logger logger = LoggerFactory
            .getLogger(OrganicTreatmentServiceImpl.class);
    @Autowired
    private SiteMapper siteMapper;
    @Autowired
    private OrganicTreatmentMapper organicTreatmentMapper;
    /**
     *@描述
     *@参数 [organicTreatmentDTO]
     *@返回值 cn.zhixiangsingle.web.responsive.ResultBean
     *@创建人 hhp
     *@创建时间 2019/11/6
     *@修改人和其它信息
     */
    @Override
    public ResultBean findOrganicTreatmentList(OrganicTreatmentDTO organicTreatmentDTO) throws Exception {
        ResultBean resultBean = new ResultBean();
        if(IsEmptyUtils.isEmpty(organicTreatmentDTO.getPage())){
            organicTreatmentDTO.setPage(1);
        }
        if (IsEmptyUtils.isEmpty(organicTreatmentDTO.getLimit())){
            organicTreatmentDTO.setLimit(10);
        }
        Integer page = organicTreatmentDTO.getPage();
        Integer limit = organicTreatmentDTO.getLimit();
        StringBuffer stringBufferJson = new StringBuffer();
        InputStream stream = getClass().getClassLoader().getResourceAsStream("json/siteData.json");
        BufferedReader br = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
        String line;
        while ((line = br.readLine()) != null) {
            stringBufferJson.append(line);
        }
        JSONObject jobj = JSON.parseObject(stringBufferJson.toString());

        List<Map<String,Object>> mainLPLs = Lists.newArrayList();
        Integer total = 0;
        int startNum = (page-1)*limit;
        int endNum = startNum+limit;
        ArrayList<Integer> totalAll = Lists.newArrayList();
        organicTreatmentDTO.setId(-1);
        organicTreatmentDTO.setThisTime("t");
        organicTreatmentDTO.setOtTime("o");
        organicTreatmentDTO.setOtName("o");
        organicTreatmentDTO.setOtImgPath("o");
        organicTreatmentDTO.setInsideTemperature("i");
        organicTreatmentDTO.setElectricBoxTemperature("e");
        organicTreatmentDTO.setThisWeight("t");
        organicTreatmentDTO.setCumulativeWeightDay("c");
        organicTreatmentDTO.setCumulativeWeight("c");
        organicTreatmentDTO.setCumulativeRunTime("c");
        organicTreatmentDTO.setStat(-1);
        if(!IsEmptyUtils.isEmpty(organicTreatmentDTO.getSdIds())){
            String[] sdIds = organicTreatmentDTO.getSdIds().split(",");
            StringBuffer stringBuffer = new StringBuffer();
            for(String sdId:sdIds){
                organicTreatmentDTO.setSdId(Integer.parseInt(sdId));
                String dataSourceName = "";
                SiteData siteData = null;
                if(!IsEmptyUtils.isEmpty(jobj.get(sdId))){
                    siteData = JSON.parseObject(jobj.get(sdId).toString(),SiteData.class);
                }
                organicTreatmentDTO.setPicturePrefix(siteData.getPicturePrefix());
                if(!IsEmptyUtils.isEmpty(siteData)){
                    dataSourceName = siteData.getDateSourceName();
                }
                if(!IsEmptyUtils.isEmpty(dataSourceName)){
                    if(IsEmptyUtils.isEmpty(stringBuffer)){
                        stringBuffer.append(sdId);
                    }else{
                        stringBuffer.append(","+sdId);
                    }
                    logger.info("--"+dataSourceName+"--");
                    DynamicDataSourceContextHolder.setDataSourceType(dataSourceName);
                    Integer totalStatus = organicTreatmentMapper.findOrganicTreatmentTotal(organicTreatmentDTO);
                    total = total + totalStatus;
                    totalAll.add(totalStatus);
                }
            }
            ArrayList<ArrayList<Integer>> startEndNums = MyStartEndUtil.getStartEndArray(totalAll,startNum,endNum);
            String[] sourceNames = stringBuffer.toString().split(",");
            for(int i=0;i<startEndNums.size();i++){
                organicTreatmentDTO.setSdId(Integer.parseInt(sourceNames[i]));
                SiteData siteData = JSON.parseObject(jobj.get(sourceNames[i]).toString(),SiteData.class);
                organicTreatmentDTO.setPicturePrefix(siteData.getPicturePrefix());
                logger.info("--"+siteData.getDateSourceName()+"--");
                DynamicDataSourceContextHolder.setDataSourceType(siteData.getDateSourceName());
                organicTreatmentDTO.setStart(startEndNums.get(i).get(0));
                organicTreatmentDTO.setEnd(startEndNums.get(i).get(1)-startEndNums.get(i).get(0));
                organicTreatmentDTO.setSdId(Integer.parseInt(sourceNames[i]));
                organicTreatmentDTO.setSiteName(siteData.getName());
                organicTreatmentDTO.setSitePhoto(siteData.getPhoto());

                List<Map<String,Object>> mainLPList = organicTreatmentMapper.findOrganicTreatmentList(organicTreatmentDTO);
                mainLPLs.addAll(mainLPList);
            }
            DynamicDataSourceContextHolder.setDataSourceType(null);
        }else{
            List<SiteVO> userSites = siteMapper.findUserSites(organicTreatmentDTO.getUserId());
            StringBuffer stringBuffer = new StringBuffer();
            for(SiteVO siteVO:userSites){
                organicTreatmentDTO.setSdId(siteVO.getSdId());
                String dataSourceName = "";
                String sdIdStr = siteVO.getSdId().toString();
                SiteData siteData = null;
                if(!IsEmptyUtils.isEmpty(jobj.get(sdIdStr))){
                    siteData = JSON.parseObject(jobj.get(sdIdStr).toString(),SiteData.class);
                }
                organicTreatmentDTO.setPicturePrefix(siteData.getPicturePrefix());
                if(!IsEmptyUtils.isEmpty(siteData)){
                    dataSourceName = siteData.getDateSourceName();
                }
                if(!IsEmptyUtils.isEmpty(dataSourceName)){
                    if(IsEmptyUtils.isEmpty(stringBuffer)){
                        stringBuffer.append(siteVO.getSdId());
                    }else{
                        stringBuffer.append(","+siteVO.getSdId());
                    }
                    logger.info("null sdIds...--"+dataSourceName+"----");
                    DynamicDataSourceContextHolder.setDataSourceType(dataSourceName);
                    Integer totalStatus = organicTreatmentMapper.findOrganicTreatmentTotal(organicTreatmentDTO);
                    total = total + totalStatus;
                    totalAll.add(totalStatus);
                }
            }
            ArrayList<ArrayList<Integer>> startEndNums = MyStartEndUtil.getStartEndArray(totalAll,startNum,endNum);
            String[] sourceNames = stringBuffer.toString().split(",");
            for(int i=0;i<startEndNums.size();i++){
                SiteData siteData = JSON.parseObject(jobj.get(sourceNames[i]).toString(),SiteData.class);
                logger.info("--"+siteData.getDateSourceName()+"--");
                organicTreatmentDTO.setPicturePrefix(siteData.getPicturePrefix());
                organicTreatmentDTO.setSdId(Integer.parseInt(sourceNames[i]));
                DynamicDataSourceContextHolder.setDataSourceType(siteData.getDateSourceName());
                organicTreatmentDTO.setStart(startEndNums.get(i).get(0));
                organicTreatmentDTO.setEnd(startEndNums.get(i).get(1)-startEndNums.get(i).get(0));
                organicTreatmentDTO.setSdId(Integer.parseInt(sourceNames[i]));
                organicTreatmentDTO.setSiteName(siteData.getName());
                organicTreatmentDTO.setSitePhoto(siteData.getPhoto());

                List<Map<String,Object>> mainLPList = organicTreatmentMapper.findOrganicTreatmentList(organicTreatmentDTO);
                mainLPLs.addAll(mainLPList);
            }
            DynamicDataSourceContextHolder.setDataSourceType(null);
        }
        resultBean.setSuccess(true);
        resultBean.setResult(mainLPLs);
        resultBean.setTotal(total);
        resultBean.setResultCode(IStatusMessage.SystemStatus.SUCCESS.getCode());
        resultBean.setMsg(IStatusMessage.SystemStatus.SUCCESS.getMessage());
        return resultBean;
    }
    /**
     *@描述
     *@参数 [organicTreatmentDTO]
     *@返回值 java.util.List<cn.zhixiangsingle.web.responsive.ResultBean>
     *@创建人 hhp
     *@创建时间 2019/11/7
     *@修改人和其它信息
     */
    @Override
    public List<ResultBean> getOrganicTreatments(OrganicTreatmentDTO organicTreatmentDTO) throws Exception {
        StringBuffer stringBufferJson = new StringBuffer();
        InputStream stream = getClass().getClassLoader().getResourceAsStream("json/siteData.json");
        BufferedReader br = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
        String line;
        while ((line = br.readLine()) != null) {
            stringBufferJson.append(line);
        }
        JSONObject jobj = JSON.parseObject(stringBufferJson.toString());

        List<ResultBean> mainLPLs = Lists.newArrayList();

        ArrayList<Integer> totalAll = Lists.newArrayList();
        organicTreatmentDTO.setThisTime("t");
        organicTreatmentDTO.setOtTime("o");
        organicTreatmentDTO.setOtName("o");
        organicTreatmentDTO.setInsideTemperature("i");
        organicTreatmentDTO.setElectricBoxTemperature("e");
        organicTreatmentDTO.setThisWeight("t");
        organicTreatmentDTO.setCumulativeWeightDay("c");
        organicTreatmentDTO.setCumulativeWeight("c");
        organicTreatmentDTO.setCumulativeRunTime("c");
        organicTreatmentDTO.setStat(-1);
        String exportTopTitle = "餐厨有机处理信息-"+DateUtils.formatDate(new Date(),"yyyy-MM-dd")+"导出";
        if(!IsEmptyUtils.isEmpty(organicTreatmentDTO.getSdIds())){
            String[] sdIds = organicTreatmentDTO.getSdIds().split(",");
            for(String sdId:sdIds){
                organicTreatmentDTO.setSdId(Integer.parseInt(sdId));
                String dataSourceName = "";
                SiteData siteData = null;
                if(!IsEmptyUtils.isEmpty(jobj.get(sdId))){
                    siteData = JSON.parseObject(jobj.get(sdId).toString(),SiteData.class);
                }
                if(!IsEmptyUtils.isEmpty(siteData)){
                    dataSourceName = siteData.getDateSourceName();
                }
                if(!IsEmptyUtils.isEmpty(dataSourceName)){
                    logger.info("--"+dataSourceName+"--");
                    DynamicDataSourceContextHolder.setDataSourceType(dataSourceName);

                    organicTreatmentDTO.setSiteName(siteData.getName());

                    Map columnWidth = new HashMap();
                    columnWidth.put(0,12000);
                    columnWidth.put(1,5000);
                    columnWidth.put(2,3000);
                    columnWidth.put(3,3000);
                    columnWidth.put(4,3000);
                    columnWidth.put(5,3000);
                    columnWidth.put(6,3000);
                    columnWidth.put(7,3000);
                    columnWidth.put(8,12000);
                    columnWidth.put(9,3000);
                    List<List<String>> topTitles = Lists.newArrayList();
                    List<String> col0 = Lists.newArrayList();
                    List<String> col1 = Lists.newArrayList();
                    List<String> col2 = Lists.newArrayList();
                    List<String> col3 = Lists.newArrayList();
                    List<String> col4 = Lists.newArrayList();
                    List<String> col5 = Lists.newArrayList();
                    List<String> col6 = Lists.newArrayList();
                    List<String> col7 = Lists.newArrayList();
                    List<String> col8 = Lists.newArrayList();
                    List<String> col9 = Lists.newArrayList();
                    col0.add(exportTopTitle);col0.add("当前累计时间");
                    col1.add(exportTopTitle);col1.add("回收时间");
                    col2.add(exportTopTitle);col2.add("操作人员");
                    col3.add(exportTopTitle);col3.add("舱内温度℃");
                    col4.add(exportTopTitle);col4.add("电箱温度℃");
                    col5.add(exportTopTitle);col5.add("当次重量");
                    col6.add(exportTopTitle);col6.add("当天累计重量");
                    col7.add(exportTopTitle);col7.add("累计重量");
                    col8.add(exportTopTitle);col8.add("累计运行时间");
                    col9.add(exportTopTitle);col9.add("当前状态");
                    topTitles.add(col0);
                    topTitles.add(col1);
                    topTitles.add(col2);
                    topTitles.add(col3);
                    topTitles.add(col4);
                    topTitles.add(col5);
                    topTitles.add(col6);
                    topTitles.add(col7);
                    topTitles.add(col8);
                    topTitles.add(col9);
                    ResultBean resultBean = new ResultBean();
                    resultBean.setMsg(siteData.getName());
                    resultBean.setObj(columnWidth);
                    List<OrganicTreatmentVO> mainLPList = organicTreatmentMapper.findAllOrganicTreatments(organicTreatmentDTO);
                    resultBean.setRows(topTitles);
                    resultBean.setResult(mainLPList);
                    mainLPLs.add(resultBean);

                }
            }
            DynamicDataSourceContextHolder.setDataSourceType(null);
        }else{
            List<SiteVO> userSites = siteMapper.findUserSites(organicTreatmentDTO.getUserId());
            StringBuffer stringBuffer = new StringBuffer();
            for(SiteVO siteVO:userSites){
                organicTreatmentDTO.setSdId(siteVO.getSdId());
                String dataSourceName = "";
                String sdIdStr = siteVO.getSdId().toString();
                SiteData siteData = null;
                if(!IsEmptyUtils.isEmpty(jobj.get(sdIdStr))){
                    siteData = JSON.parseObject(jobj.get(sdIdStr).toString(),SiteData.class);
                }

                if(!IsEmptyUtils.isEmpty(siteData)){
                    dataSourceName = siteData.getDateSourceName();
                }
                if(!IsEmptyUtils.isEmpty(dataSourceName)){

                    logger.info("--"+siteData.getDateSourceName()+"--");

                    DynamicDataSourceContextHolder.setDataSourceType(dataSourceName);

                    organicTreatmentDTO.setSiteName(siteData.getName());

                    Map columnWidth = new HashMap();
                    columnWidth.put(0,12000);
                    columnWidth.put(1,5000);
                    columnWidth.put(2,3000);
                    columnWidth.put(3,3000);
                    columnWidth.put(4,3000);
                    columnWidth.put(5,3000);
                    columnWidth.put(6,3000);
                    columnWidth.put(7,3000);
                    columnWidth.put(8,12000);
                    columnWidth.put(9,3000);
                    List<List<String>> topTitles = Lists.newArrayList();
                    List<String> col0 = Lists.newArrayList();
                    List<String> col1 = Lists.newArrayList();
                    List<String> col2 = Lists.newArrayList();
                    List<String> col3 = Lists.newArrayList();
                    List<String> col4 = Lists.newArrayList();
                    List<String> col5 = Lists.newArrayList();
                    List<String> col6 = Lists.newArrayList();
                    List<String> col7 = Lists.newArrayList();
                    List<String> col8 = Lists.newArrayList();
                    List<String> col9 = Lists.newArrayList();
                    col0.add(exportTopTitle);col0.add("当前累计时间");
                    col1.add(exportTopTitle);col1.add("回收时间");
                    col2.add(exportTopTitle);col2.add("操作人员");
                    col3.add(exportTopTitle);col3.add("舱内温度℃");
                    col4.add(exportTopTitle);col4.add("电箱温度℃");
                    col5.add(exportTopTitle);col5.add("当次重量");
                    col6.add(exportTopTitle);col6.add("当天累计重量");
                    col7.add(exportTopTitle);col7.add("累计重量");
                    col8.add(exportTopTitle);col8.add("累计运行时间");
                    col9.add(exportTopTitle);col9.add("当前状态");
                    topTitles.add(col0);
                    topTitles.add(col1);
                    topTitles.add(col2);
                    topTitles.add(col3);
                    topTitles.add(col4);
                    topTitles.add(col5);
                    topTitles.add(col6);
                    topTitles.add(col7);
                    topTitles.add(col8);
                    topTitles.add(col9);
                    ResultBean resultBean = new ResultBean();
                    resultBean.setMsg(siteData.getName());
                    resultBean.setObj(columnWidth);
                    List<OrganicTreatmentVO> mainLPList = organicTreatmentMapper.findAllOrganicTreatments(organicTreatmentDTO);
                    resultBean.setRows(topTitles);
                    resultBean.setResult(mainLPList);
                    mainLPLs.add(resultBean);
                }
            }
            DynamicDataSourceContextHolder.setDataSourceType(null);
        }
        return mainLPLs;
    }
}
